<script setup lang="ts">
import { ref, markRaw, computed } from "vue";
import { useColumns } from "./columns";
import Plus from "~icons/ep/plus";
import AddFill from "~icons/ep/plus";
import Delete from "~icons/ep/delete";
import Empty from "@/assets/common/empty.svg?component";
import UploadIcon from "~icons/ri/upload-2-line?width=26&height=26";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import "plus-pro-components/es/components/dialog-form/style/css";
// import { getProductInfo, setProductInfo, addProductInfo } from "@/api/finance";
import {
  getCats,
  getProductInfo,
  addProductInfo,
  setProductSale,
  setProductInfo
} from "@/api/mall";
import { fixImageUrl, handleImagesUpload } from "@/utils/common";
defineOptions({
  name: "MallProduct"
});
import {
  PlusSearch,
  type PlusColumn,
  type FieldValues,
  PlusDialogForm
} from "plus-pro-components";
import {
  type Action,
  genFileId,
  ElMessageBox,
  ElMessage,
  UploadInstance,
  UploadProps,
  UploadRawFile
} from "element-plus";

import { useMenu } from "@/utils/power";
const power = useMenu(["add", "edit", "unsale"]);

const previewImageUrl = ref();
const previewImageName = ref();
const showPreviewImage = ref(false);
const edit = ref(false);

const productImageRef = ref<UploadInstance>();
const productJSImageRef = ref<UploadInstance>();
const productDescImageRef = ref<UploadInstance>();

const rules = {
  title: [
    {
      required: false,
      message: "商品标题必填"
    }
  ],
  front_image: [
    {
      required: false,
      message: "商品图片必填"
    }
  ],
  images: [
    {
      required: false,
      message: "介绍图片必填"
    }
  ]
};

const formColumns: PlusColumn[] = [
  {
    label: "商品标题",
    width: 120,
    prop: "name",
    valueType: "input"
  },
  {
    label: "简单描述",
    width: 120,
    prop: "description",
    valueType: "input"
  },
  {
    label: "商品类型",
    prop: "goods_type",
    valueType: "select",
    options: [
      {
        label: "现金商品",
        value: 2
      },
      {
        label: "积分商品",
        value: 3
      }
    ]
  },
  {
    label: "商品分类",
    width: 100,
    labelWidth: 120,
    prop: "category_id",
    valueType: "select",
    options: async () => {
      try {
        const res = await getCats();
        return res.data.map(item => {
          return { label: item.name, value: item.id };
        });
      } catch (error) {
        console.log(error, "error");
        return [];
      }
    }
  },
  {
    label: "商品图片",
    width: 120,
    prop: "front_image",
    valueType: "img",
    tooltip: "上传商品图片"
  },
  {
    label: "介绍图片",
    width: 120,
    prop: "images",
    valueType: "img",
    tooltip: "上传商品图片"
  },
  {
    label: "价格",
    width: 120,
    prop: "price",
    valueType: "input",
    tooltip: "产品价格"
  },
  {
    label: "排序",
    width: 120,
    prop: "sort",
    valueType: "input-number"
  },
  {
    label: "是否首页",
    prop: "is_home",
    valueType: "radio",
    options: [
      {
        label: "是",
        value: 1
      },
      {
        label: "否",
        value: 0
      }
    ]
  },
  {
    label: "是否实名",
    prop: "is_real",
    valueType: "radio",
    options: [
      {
        label: "是",
        value: 1
      },
      {
        label: "否",
        value: 0
      }
    ]
  },
  {
    label: "是否爆款",
    prop: "is_bestseller",
    valueType: "radio",
    options: [
      {
        label: "是",
        value: 1
      },
      {
        label: "否",
        value: 0
      }
    ]
  },
  {
    label: "用户最大购买次数",
    width: 120,
    prop: "only_buy",
    valueType: "input-number",
    fieldProps: { precision: 0, step: 1, min: 1 }
  },
  {
    label: "单次购买最大数",
    width: 120,
    prop: "only_count",
    valueType: "input-number",
    fieldProps: { precision: 0, step: 1, min: 1 }
  },
  {
    label: "商品描述",
    prop: "descriptions"
  },
  {
    label: "商品规格",
    prop: "skus"
  },
  {
    label: "是否发布",
    prop: "on_sale",
    valueType: "radio",
    options: [
      {
        label: "上架",
        value: 1
      },
      {
        label: "下架",
        value: 0
      }
    ]
  }
];

const visible = ref(false);
const values = ref({});
const props = defineProps({
  type: {
    type: Number,
    default: 1
  }
});
const {
  loading,
  columns,
  dataList,
  pagination,
  loadingConfig,
  adaptiveConfig,
  onSizeChange,
  onKeywordChange,
  loadData,
  onCurrentChange
} = useColumns(props.type);

const columnsRef = computed(() => {
  if (power.value.edit || power.value.unsale) {
    return columns;
  }
  const columnsCopy = [...columns];
  return columnsCopy.slice(0, -1);
});

function deleteClick(row) {
  ElMessageBox.confirm("是否删除", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    draggable: true,
    type: "error",
    icon: markRaw(Delete),
    callback: async (action: Action) => {
      // 在这里执行删除操作
      if (action === "confirm") {
        console.log("执行删除操作");
        try {
          const params = {
            orderId: row.fgId,
            isDelete: 1
          };
          const res = await setProductInfo(params);
          loadData();
          ElMessage.success("删除成功");
        } catch (error) {
          console.log(error, "error");
        }
      }
    }
  });
}

const imageFile = (path: any) => {
  return path.split(",").map((path: any) => {
    return { url: fixImageUrl(path), name: path.split("/").pop() };
  });
};
const editClick = async row => {
  console.log(
    "%crow===编辑>>>: ",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    row
  );
  try {
    const res = await getProductInfo(row.goodsId);
    Object.assign(values.value, res.data);
    // values.value = { ...res.data };
    console.log(
      "%cres===>>>",
      "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
      "返回的",
      res,
      values.value
    );
    edit.value = true;
    visible.value = true;
  } catch (error) {
    console.log(error, "error");
  }
};
const addProduct = () => {
  console.log("%c点击了添加商品>>>: ", "color: MidnightBlue; font-size: 20px;");
  edit.value = false;
  values.value = {};
  visible.value = true;
};
const confirmLoading = ref(false);
const handleSubmit = async (value: FieldValues) => {
  const updatedValues = { ...values.value };
  console.log("value submit", updatedValues);

  confirmLoading.value = true;
  if (edit.value) {
    try {
      await setProductInfo(updatedValues);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      loadData();
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  } else {
    try {
      await addProductInfo(updatedValues);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      loadData();
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  }
};
const handleIconImageSuccess: UploadProps["onSuccess"] = (res, file) => {
  values.value.front_image = res.data;
};
const handleIconImageRemove: UploadProps["onRemove"] = (file, files) => {
  values.value.front_image = undefined;
};
/// 超出limit限制 先清空文件列表再执行上传
const handleIconImageExceed: UploadProps["onExceed"] = files => {
  productImageRef.value?.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  productImageRef.value?.handleStart(file);
  productImageRef.value?.submit();
};
const handlePreviewImage: UploadProps["onPreview"] = file => {
  previewImageName.value = file.name;
  previewImageUrl.value = file.url;
  showPreviewImage.value = true;
};

const handleImagesSuccess: UploadProps["onSuccess"] = (res, file, files) => {
  if (res.code != 0) {
    ElMessage.error(res.msg);
    return;
  }
  const image = res.data;
  if (!values.value.images || values.value.images.length == 0) {
    values.value.images = [image];
  } else {
    values.value.images.push(image);
  }
};
const handleImagesRemove: UploadProps["onRemove"] = (file, files) => {
  values.value.images = files.map(item => item.url);
  console.log("imagesRemove", values.value.images, file, files);
};
/// 超出limit限制 先清空文件列表再执行上传
const handleImagesExceed: UploadProps["onExceed"] = files => {
  ElMessage.error("最多上传5张图片");
};

const imageList = computed(() => {
  const images = values.value.images as string;
  if (images && images.length > 0) {
    return images.map((path: any) => {
      return { url: fixImageUrl(path), name: path.split("/").pop() };
    });
  }
  return [];
});

const handleDescImagesSuccess: UploadProps["onSuccess"] = (
  res,
  file,
  files
) => {
  if (res.code != 0) {
    ElMessage.error(res.msg);
    return;
  }
  const image = { type: 1, content: res.data };
  if (!values.value.descriptions || values.value.descriptions.length == 0) {
    values.value.descriptions = [image];
  } else {
    values.value.descriptions.push(image);
  }
};
const handleDescImagesRemove: UploadProps["onRemove"] = (file, files) => {
  values.value.descriptions = files.map(item => {
    return { type: 1, content: item.url };
  });
  console.log("imagesRemove", values.value.descriptions, file, files);
};
/// 超出limit限制 先清空文件列表再执行上传
const handleDescImagesExceed: UploadProps["onExceed"] = files => {
  ElMessage.error("最多上传20张图片");
};

const descImageList = computed(() => {
  const images = values.value.descriptions;
  if (images && images.length > 0) {
    return images.map((item: any) => {
      const path = item.content;
      return { url: fixImageUrl(path), name: path.split("/").pop() };
    });
  }
  return [];
});

const formRef = ref();

const searchColumns: PlusColumn[] = [
  {
    label: "搜索",
    width: 200,
    prop: "goodsName",
    valueType: "copy",
    tooltip: "请输入搜索关键词"
  },
  {
    label: "商品分类",
    width: 100,
    labelWidth: 120,
    prop: "categoryId",
    valueType: "select",
    options: async () => {
      try {
        const res = await getCats();
        return res.data.map(item => {
          return { label: item.name, value: item.id };
        });
      } catch (error) {
        console.log(error, "error");
        return [];
      }
    }
  },
  {
    label: "商品类别",
    prop: "goodsType",
    labelWidth: 120,
    valueType: "select",
    options: [
      {
        label: "现金商品",
        value: 2,
        color: "red"
      },
      {
        label: "积分商品",
        value: 3,
        color: "red"
      }
    ]
  },
  {
    label: "是否爆款",
    prop: "isBestseller",
    labelWidth: 120,
    valueType: "select",
    options: [
      {
        label: "否",
        value: 0,
        color: "red"
      },
      {
        label: "是",
        value: 1,
        color: "red"
      }
    ]
  },

  {
    label: "是否首页",
    prop: "isHome",
    labelWidth: 120,
    valueType: "select",
    options: [
      {
        label: "否",
        value: 0,
        color: "red"
      },
      {
        label: "是",
        value: 1,
        color: "red"
      }
    ]
  },
  {
    label: "是否上架",
    prop: "onSale",
    labelWidth: 120,
    valueType: "select",
    options: [
      {
        label: "否",
        value: 0,
        color: "red"
      },
      {
        label: "是",
        value: 1,
        color: "red"
      }
    ]
  }
];

const defaultSearchState = ref({});

const handleSearch = (value: any, old: any) => {
  console.log("search", value, old);
  onKeywordChange(value);
};
const handleChange = (value: any, target: any) => {
  if (target.prop == "goodsName") {
    return;
  }
  console.log("searchChange", value, target);
  onKeywordChange(value);
};
const handleReset = value => {
  console.log("reset", value);
  onKeywordChange(value);
};

const skus_columns: TableColumnList = [
  {
    label: "标题",
    slot: "title"
  },
  {
    label: "图片",
    slot: "sku_image"
  },
  {
    label: "价格",
    slot: "price"
  },
  {
    label: "积分",
    slot: "points"
  },
  {
    label: "库存",
    slot: "stock"
  },
  {
    label: "操作",
    slot: "operation"
  }
];
const onAddSku = () => {
  if (values.value.skus) {
    values.value.skus.push({});
  } else {
    values.value.skus = [{}];
  }
};
const onDelSku = row => {
  const index = values.value.skus.indexOf(row);
  if (index !== -1) values.value.skus.splice(index, 1);
};

const handleSkuImageSuccess: UploadProps["onSuccess"] = (res, file, files) => {
  console.log(res, file, files);
  for (let i = 0; i < values.value.skus.length; i++) {
    const imageUrl = files[i].response ? files[i].response.data : files[i].url;
    values.value.skus[i].sku_image = imageUrl;
  }
  // values.value.iconimage = res.data;
};
const handleSkuImageRemove: UploadProps["onRemove"] = (file, files) => {
  for (let i = 0; i < values.value.skus.length; i++) {
    const imageUrl = files[i].response ? files[i].response.data : files[i].url;
    values.value.skus[i].sku_image = imageUrl;
  }
};
/// 超出limit限制 先清空文件列表再执行上传
const handleSkuImageExceed: UploadProps["onExceed"] = (files, upFiles) => {
  console.log(files, upFiles);
  ElMessage.error("请先删除后再选择图片");
  // productImageRef.value?.clearFiles();
  // const file = files[0] as UploadRawFile;
  // file.uid = genFileId();
  // productImageRef.value?.handleStart(file);
  // productImageRef.value?.submit();
};
const handleSale = async row => {
  console.log("下架", row);
  try {
    const res = await setProductSale(row.goodsId);
    ElMessage.success("操作成功");
    loadData();
  } catch (error) {
    console.log(error, "error");
  }
};
</script>

<template>
  <ElCard>
    <template #header>
      <ElPageHeader :icon="null">
        <template #title>
          <h3>商品管理</h3>
        </template>
        <template v-if="power.add" #extra>
          <el-button type="primary" @click="addProduct">
            <el-icon :size="15" color="#fff">
              <IconifyIconOffline :icon="Plus" />
            </el-icon>
            添加商品
          </el-button>
        </template>
        <PlusSearch
          :defaultValues="defaultSearchState"
          class="mt-5"
          :columns="searchColumns"
          :hasUnfold="false"
          @reset="handleReset"
          @change="handleChange"
          @search="handleSearch"
        />
      </ElPageHeader>
    </template>
    <pure-table
      ref="tableRef"
      showOverflowTooltip
      border
      adaptive
      :adaptiveConfig="adaptiveConfig"
      row-key="id"
      alignWhole="center"
      :loading="loading"
      :loading-config="loadingConfig"
      :data="dataList"
      :columns="columnsRef"
      :pagination="pagination"
      @page-size-change="onSizeChange"
      @page-current-change="onCurrentChange"
    >
      <template #frontImage="{ row, index }">
        <el-image
          preview-teleported
          loading="lazy"
          :src="fixImageUrl(row.frontImage)"
          :preview-src-list="dataList.map(v => fixImageUrl(v.frontImage))"
          :initial-index="index"
          fit="cover"
          class="w-[50px] h-[50px]"
        />
      </template>
      <template #images="{ row }">
        <div class="flex flex-row flex-wrap gap-2">
          <el-image
            v-for="item in row.images"
            :key="item.id"
            preview-teleported
            loading="lazy"
            :src="fixImageUrl(item)"
            :preview-src-list="row.images.map(v => fixImageUrl(v))"
            fit="cover"
            class="w-[50px] h-[50px]"
          />
        </div>
      </template>
      <template #onSale="{ row }">
        <el-tag v-if="row.onSale == 1" type="success">上架</el-tag>
        <el-tag v-else type="danger">下架</el-tag>
      </template>
      <template #operation="{ row }">
        <el-button
          v-if="power.edit"
          type="primary"
          size="small"
          @click="editClick(row)"
          >编辑</el-button
        >
        <el-button
          v-if="power.unsale"
          :type="row.onSale == 1 ? 'danger' : 'primary'"
          size="small"
          @click="handleSale(row)"
        >
          {{ row.onSale == 1 ? "下架" : "上架" }}
        </el-button>
      </template>
    </pure-table>
    <PlusDialogForm
      ref="formRef"
      v-model:visible="visible"
      v-model="values"
      :form="{ columns: formColumns, rules, labelWidth: 120 }"
      :dialog="{ confirmLoading, width: '80%' }"
      :title="edit ? '编辑商品' : '添加商品'"
      @confirm="handleSubmit"
    >
      <template #plus-field-front_image>
        <el-upload
          ref="productImageRef"
          drag
          :auto-upload="true"
          list-type="picture-card"
          :limit="1"
          :http-request="handleImagesUpload"
          :file-list="
            values.front_image && values.front_image.length > 0
              ? imageFile(values.front_image)
              : []
          "
          :on-success="handleIconImageSuccess"
          :on-remove="handleIconImageRemove"
          :on-preview="handlePreviewImage"
          :on-exceed="handleIconImageExceed"
        >
          <div>
            <UploadIcon class="m-auto mb-2" />
            可点击或拖拽上传
          </div>
        </el-upload>
      </template>

      <template #plus-field-images>
        <el-upload
          ref="productJSImageRef"
          drag
          :auto-upload="true"
          :http-request="handleImagesUpload"
          list-type="picture-card"
          :limit="5"
          :file-list="imageList"
          :on-success="handleImagesSuccess"
          :on-remove="handleImagesRemove"
          :on-preview="handlePreviewImage"
          :on-exceed="handleImagesExceed"
        >
          <div>
            <UploadIcon class="m-auto mb-2" />
            可点击或拖拽上传
          </div>
        </el-upload>
      </template>
      <template #plus-field-skus>
        <pure-table
          border
          row-key="id"
          align-whole="center"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          :data="values.skus"
          :columns="skus_columns"
        >
          <template #empty>
            <Empty fill="var(--el-svg-monochrome-grey)" class="m-auto" />
          </template>
          <template #append>
            <el-button
              type="success"
              class="w-full my-2!"
              :icon="useRenderIcon(AddFill)"
              @click="onAddSku"
            >
              添加一行数据
            </el-button>
          </template>
          <template #title="{ row }">
            <el-input
              v-model="row.title"
              placeholder="请输入标题"
              style="width: 100%"
            />
          </template>
          <template #sku_image="{ row }">
            <el-upload
              :auto-upload="true"
              :show-file-list="true"
              list-type="picture"
              :limit="1"
              :http-request="handleImagesUpload"
              :file-list="
                row.sku_image && row.sku_image.length > 0
                  ? imageFile(row.sku_image)
                  : []
              "
              :on-success="handleSkuImageSuccess"
              :on-remove="handleSkuImageRemove"
              :on-preview="handlePreviewImage"
              :on-exceed="handleSkuImageExceed"
            >
              <el-button
                v-if="!row.sku_image || row.sku_image.length == 0"
                size="small"
                type="primary"
                >选择图片</el-button
              >
            </el-upload>
          </template>
          <template #price="{ row }">
            <el-input-number
              v-model="row.price"
              :disabled="values.goods_type != 2"
              :precision="0"
              :step="100"
              placeholder="请输入价格(分)"
              style="width: 100%"
            />
          </template>
          <template #points="{ row }">
            <el-input-number
              v-model="row.points"
              :disabled="values.goods_type != 3"
              :precision="0"
              :step="100"
              placeholder="请输入积分"
              style="width: 100%"
            />
          </template>
          <template #stock="{ row }">
            <el-input-number
              v-model="row.stock"
              :precision="0"
              :step="100"
              placeholder="请输入库存"
              style="width: 100%"
            />
          </template>
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              type="danger"
              :icon="useRenderIcon(Delete)"
              @click="onDelSku(row)"
            />
          </template>
        </pure-table>
      </template>
      <template #plus-field-descriptions>
        <el-upload
          ref="productDescImageRef"
          drag
          :auto-upload="true"
          :http-request="handleImagesUpload"
          list-type="picture-card"
          :limit="20"
          :file-list="descImageList"
          :on-success="handleDescImagesSuccess"
          :on-remove="handleDescImagesRemove"
          :on-preview="handlePreviewImage"
          :on-exceed="handleDescImagesExceed"
        >
          <div>
            <UploadIcon class="m-auto mb-2" />
            可点击或拖拽上传
          </div>
        </el-upload>
      </template>
    </PlusDialogForm>
    <el-dialog v-model="showPreviewImage">
      <img w-full :src="previewImageUrl" :alt="previewImageName" />
    </el-dialog>
  </ElCard>
</template>

<style scoped></style>
